import type { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';
import type { AxiosTransform, CreateAxiosOptions } from './types/staxios';

import { Toast } from 'vant';
import STAxios from './STAxios';
import { deepMerge } from '/@/utils';
import { Base64 } from 'js-base64';
import { useUserStoreWithOut } from '/@/store/user';

const transform: AxiosTransform = {
  requestInterceptors(config: AxiosRequestConfig) {
    const userStore = useUserStoreWithOut();
    if (userStore.getToken) {
      return deepMerge(config, {
        headers: {
          'Paas-Auth': userStore.getToken
        }
      });
    }
    return config;
  },
  responseInterceptors(res: AxiosResponse<any>) {
    return res;
  },
  requestCatchHook: (e: Error | AxiosError) => {
    if (e.message) {
      Toast(e.message);
    }
    return Promise.reject(e);
  }
};

const createAxios = (opt?: Partial<CreateAxiosOptions>) => {
  return new STAxios(
    deepMerge(
      {
        timeout: 40 * 1000,
        transform,
        headers: {
          Authorization: `Basic ${Base64.encode(`saber:saber_secret`)}`
        }
      },
      opt || {}
    )
  );
};

export default createAxios();
